# Copyright (C) 2007 - Michael Opitz
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
import gtk
import epiphany

_ui_str = """
<ui>
	<menubar name="menubar">
		<menu name="ToolsMenu" action="Tools">
			<separator/>
			<menuitem name="PyTabRestore" action="PyTabRestore"/>
		</menu>
	</menubar>
</ui>
"""

def _restore_tab_cb(action, window):
	# restore the last closed tab
	if(len(window._py_restore_urls) > 0):
		notebook = window.get_notebook()
		position = notebook.get_n_pages() - 1
		prev_tab = notebook.get_nth_page(position)
		shell = epiphany.ephy_shell_get_default()
		shell.new_tab(window, prev_tab, window._py_restore_urls.pop(),
				epiphany.NEW_TAB_IN_EXISTING_WINDOW | 
				epiphany.NEW_TAB_OPEN_PAGE | 
				epiphany.NEW_TAB_JUMP)

_actions = [('PyTabRestore', None, '_Restore Tab', "<control><shift>T", 
		"Restore a previosly closed tab", _restore_tab_cb),]
def attach_window(window):
	window._py_restore_urls = []
	# create the menu entry
	ui_manager = window.get_ui_manager()
	group = gtk.ActionGroup('PyTabRestore')
	group.add_actions(_actions, window)
	ui_manager.insert_action_group(group, -1)
	ui_id = ui_manager.add_ui_from_string(_ui_str)

	window._python_tab_restore_window_data = (group, ui_id)

def detach_window(window):
	# delete our list...
	del window._py_restore_urls 
	# delete the epiphany stuff
	group, ui_id = window._python_tab_restore_window_data
	del window._python_tab_restore_window_data

	ui_manager = window.get_ui_manager()
	ui_manager.remove_ui(ui_id)
	ui_manager.remove_action_group(group)
	ui_manager.ensure_update()

def detach_tab(window, tab):
	# when a tab is closed we are appening the url of the closed tab to our
	# list
	window._py_restore_urls.append(tab.get_embed().get_location(True))

